package com.colin.juc.java8;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author zhaodong 2021/5/29 14:1502
 * email: colinzhaodong@gmail.com
 * desc: 分治任务
 */
public class ForkAndJoin {
    /**
     * 递归任务
     */
    private static class Fibonacci extends
            RecursiveTask<Integer> {
        final int n;
        Fibonacci(int n){this.n = n;}
        @Override
        protected Integer compute(){
            if (n <= 1) {
                return n;
            }
            Fibonacci f1 =
                    new Fibonacci(n - 1);
            // 创建子任务
            f1.fork();
            Fibonacci f2 =
                    new Fibonacci(n - 2);
            // 等待子任务结果，并合并结果
            return f2.compute() + f1.join();
        }
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        // 创建分治任务
        Fibonacci fib =
                new Fibonacci(3);
        Integer result = forkJoinPool.invoke(fib);
        System.out.println(result);
    }


}
